package httputils

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"net/http"
)

var Logger *logrus.Logger

func Response404(w http.ResponseWriter) {
	w.WriteHeader(http.StatusNotFound)
}

func Response302(w http.ResponseWriter, url string) {
	w.Header().Set("Location", url)
	w.WriteHeader(http.StatusFound)
}

func ResponseWithError(w http.ResponseWriter, err error) {
	switch e := err.(type) {
	case Error:
		if nil != Logger {
			Logger.Printf("Http %d - %s", e.Status(), e.Error())
		}
		ResponseWithJSON(w, e.Status(), e.Error(), nil)
	default:
		if nil != Logger {
			Logger.Printf("Http 500 - %s", e)
		}
		ResponseWithJSON(w, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError), nil)
	}
}

func ResponseWithJSON(w http.ResponseWriter, code int, msg string, payload interface{}) {
	resp, _ := json.Marshal(respJSON{
		Code: code,
		Msg:  msg,
		Data: payload,
	})
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	//log.Printf("ResponseWithJSON: code %d,body %s",code,string(resp))
	w.Write(resp)
}
